package com.library.repository.impl;

import com.library.entity.Book;
import com.library.entity.BookCase;
import com.library.repository.BookRepository;
import com.library.utils.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {

    /**
     * 根据页数查询数据
     * @param index
     * @param limit
     * @return
     */
    @Override
    public List<Book> findAll(int index, int limit) {
        //执行sql语句进行查询
        Connection connection = JDBCTools.getConnection();
        String sql = "select * from book,bookcase where book.bookcaseid = bookcase.id limit ?,?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Book> list = new ArrayList<>();
        try {
            //设置sql语句地参数，分别为当前页数和每页展示的条目数
            statement = connection.prepareStatement(sql);
            statement.setInt(1, index);
            statement.setInt(2,limit);
            resultSet = statement.executeQuery();
            //将获取到的数据保存成对象形式加入到数据中
            while (resultSet.next()) {
                list.add(new Book(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3),
                        resultSet.getString(4), resultSet.getInt(5), resultSet.getDouble(6),
                        new BookCase(resultSet.getInt(9), resultSet.getString(10))));
            }
        } catch (SQLException e) {
            System.out.println("出问题了");
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, resultSet);
        }
        return list;
    }

    /**
     * 统计书籍的总数，方便计算总页数
     * @return
     */
    @Override
    public int count() {
        //执行sql语句进行查询
        Connection connection = JDBCTools.getConnection();
        String sql = "select count(*) from book,bookcase where book.bookcaseid = bookcase.id";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Integer count = 0;
        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            //将获取到的数据保存成对象形式加入到数据中
            while (resultSet.next()){
                count = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            System.out.println("出问题了");
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, resultSet);
        }
        return count;
    }
}
